package com.lsk.mobile;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.lsk.bean.WxaBean;
import com.lsk.util.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * 小程序service
 */
public class AppletService {

    private static String jsCode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
    Cache cache= Redis.use();

    public ReturnData getSessionKeyService(String jsCode){

        Map<String, String> params = new HashMap();
        params.put("appid", "wx49ed6c99c11865fe");
        params.put("secret", "c1d46b7ca68d9448f131edcb82117a4a");
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");
        String para = PaymentKit.packageSign(params, false);
        String url = jsCode2sessionUrl + "?" + para;
        ApiResult apiResult=new ApiResult(HttpUtils.get(url));
        Syslog.info(apiResult.getJson());

        ReturnData returnData= upMemberService(apiResult,3);
        /*查询当前uniounId是否有会员*/
        /*此处先用openId代替（当用户没有关注过小程序，登陆过app等时间，获取不到unionid）  以后时间充足了，再进行优化*/
        return returnData;

    }
    public ReturnData getSessionKeyService1(String jsCode){
        WxaBean wxaBean=new WxaBean();
        Map<String, String> params = new HashMap();
        params.put("appid", "wx9952e6daeb21a91c");
        params.put("secret", "f0bb7fa2ba26274a494a2099dc95128c");
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");
        String para = PaymentKit.packageSign(params, false);
        String url = jsCode2sessionUrl + "?" + para;
        ApiResult apiResult=new ApiResult(HttpUtils.get(url));
        Syslog.info(apiResult.getJson());

        ReturnData returnData= upMemberService(apiResult,4);
        /*查询当前uniounId是否有会员*/
        /*此处先用openId代替（当用户没有关注过小程序，登陆过app等时间，获取不到unionid）  以后时间充足了，再进行优化*/
        return returnData;
    }

    public ReturnData getSessionKeyService2(String jsCode){
        WxaBean wxaBean=new WxaBean();
        Map<String, String> params = new HashMap();
        params.put("appid", "wx1ebcfe4959961720");
        params.put("secret", "842b54508cd6e0a57bd492db197791d0");
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");
        String para = PaymentKit.packageSign(params, false);
        String url = jsCode2sessionUrl + "?" + para;
        ApiResult apiResult=new ApiResult(HttpUtils.get(url));
        Syslog.info(apiResult.getJson());

        ReturnData returnData= upMemberService(apiResult,5);
        /*查询当前uniounId是否有会员*/
        /*此处先用openId代替（当用户没有关注过小程序，登陆过app等时间，获取不到unionid）  以后时间充足了，再进行优化*/
        return returnData;
    }

    public ReturnData getSessionKeyService3(String jsCode){
        WxaBean wxaBean=new WxaBean();
        Map<String, String> params = new HashMap();
        params.put("appid", "wxb4e3b51baa575662");
        params.put("secret", "e2ed0a75ae67f1686a724256315cd106");
        params.put("js_code", jsCode);
        params.put("grant_type", "authorization_code");
        String para = PaymentKit.packageSign(params, false);
        String url = jsCode2sessionUrl + "?" + para;
        ApiResult apiResult=new ApiResult(HttpUtils.get(url));
        Syslog.info(apiResult.getJson());

        ReturnData returnData= upMemberService(apiResult,6);
        /*查询当前uniounId是否有会员*/
        /*此处先用openId代替（当用户没有关注过小程序，登陆过app等时间，获取不到unionid）  以后时间充足了，再进行优化*/
        return returnData;
    }





    /**
     * 会员处理
     */
    public ReturnData upMemberService(ApiResult apiResult, final int type){

        final ReturnData returnData=new ReturnData(true);

        final String openId=apiResult.getStr("openid");

        String sql="SELECT *from sys_user where wxOpenId='"+openId+"'";

        Record sysUser=Db.findFirst(sql);

        if (sysUser==null){

            final String userId=UuidUtil.get32UUID();
            final String salt = UuidUtil.get6UUID();  //盐值
            final String encodePassword = MD5.md5("123456" + salt); //password+salt 使用md加密后

            //开启事务
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {

                     final String strType=type+"";

                    String userNameRandom = RadomUtil.getName();//生成一个随机名字
                    try {
                        Record sysUser=new Record();

                        Db.save("sys_user", sysUser.set("id", userId).set("userName", userNameRandom)
                                .set("userCode", "wxa"+Tools.getRandomNum()+Tools.getRandomNum()).set("password", encodePassword).set("salt", salt)
                                .set("locked", 0).set("type", 2).set("wxOpenId",openId)

                        );

                        Record memberInfo=new Record();

                        Db.save("yx_member", memberInfo.set("id", UuidUtil.get32UUID())
                                .set("name", userNameRandom).set("userId", userId).set("type",strType).set("source",strType));

                        String token = AES.AESEncode(userId);

                        Map<String, Record> userMap = new HashMap<>();

                        userMap.put("memberInfo", memberInfo);

                        cache.setex(token, 60 * 60 * 24, userMap);

                        Map result=new HashMap();

                        result.put("memberInfo",memberInfo);


                        result.put("token",token);



                        returnData.setResult(true);
                        returnData.setData(memberInfo);

                    } catch (Exception e) {

                        Syslog.error(e);
                        return false;//回滚
                    }
                    return true;
                }
            });

        }else {

            String id=sysUser.getStr("id");

            String memberSql="SELECT *from yx_member where userId='"+id+"'";

            Record record=Db.findFirst(memberSql);


            String token = AES.AESEncode(id);

            Map<String, Record> userMap = new HashMap<>();

            userMap.put("memberInfo", record);

            cache.setex(token, 60 * 60 * 24, userMap);

            Map result=new HashMap();

            result.put("memberInfo",record);

            result.put("token",token);



            returnData.setResult(true);

            returnData.setData(result);
        }

        return returnData;

    }


    /**
     * 支付宝会员处理
     */
    public ReturnData apiupMemberService(String useId, String nick_name2, final String heardUrl){

        final ReturnData returnData=new ReturnData(true);

        final String alipayId=useId;

        String sql="SELECT *from sys_user where alipayId='"+alipayId+"'";

        Record sysUser=Db.findFirst(sql);

        if (sysUser==null){

            final String userId=UuidUtil.get32UUID();
            final String salt = UuidUtil.get6UUID();  //盐值
            final String encodePassword = MD5.md5("123456" + salt); //password+salt 使用md加密后
            final String nick_name=nick_name2;

            final String heardUrl1=heardUrl;
            //开启事务
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    String userNameRandom = RadomUtil.getName();//生成一个随机名字
                    try {
                        Record sysUser=new Record().set("id", userId).set("userName", nick_name)
                                .set("userCode", "ali"+Tools.getRandomNum()+Tools.getRandomNum()).set("password", encodePassword).set("salt", salt)
                                .set("locked", 0).set("type", 2).set("alipayId",alipayId).set("heardUrl",heardUrl1);

                        Db.save("sys_user", sysUser);

                        Record memberInfo=new Record().set("id", UuidUtil.get32UUID()).set("source",2)
                                .set("alipayId",alipayId)
                                .set("userId", userId).set("type",2).set("name",nick_name).set("heardUrl",heardUrl1);

                        Db.save("yx_member", memberInfo);

                        String token = AES.AESEncode(userId);

                        Map<String, Record> userMap = new HashMap<>();

                        userMap.put("memberInfo", memberInfo);

                        cache.setex(token, 60 * 60 * 24, userMap);

                        Map result=new HashMap();

                        result.put("memberInfo",memberInfo);

                        result.put("token",token);

                        returnData.setResult(true);
                        returnData.setData(result);

                    } catch (Exception e) {

                        Syslog.error(e);
                        return false;//回滚
                    }
                    return true;
                }
            });

        }else {

            String id=sysUser.getStr("id");

            String memberSql="SELECT *from yx_member where userId='"+id+"'";

            Record record=Db.findFirst(memberSql);

            record.set("name",nick_name2).set("heardUrl",heardUrl);

            Db.update("yx_member","id",record);

            String token = AES.AESEncode(id);

            Map<String, Record> userMap = new HashMap<>();

            userMap.put("memberInfo", record);

            cache.setex(token, 60 * 60 * 24, userMap);

            Map result=new HashMap();

            result.put("memberInfo",record);

            result.put("token",token);

            returnData.setResult(true);

            returnData.setData(result);
        }

        return returnData;

    }

    /**
     * 刷新token
     */
    public ReturnData refreshTokenService(String userId){

        String memberSql="SELECT *from yx_member where userId='"+userId+"'";

        Record memberInfo=Db.findFirstByCache("memberInfo",MD5.md5(memberSql),memberSql);

        String sql="SELECT *from sys_user where id='"+userId+"'";

        Record userInfo=Db.findFirstByCache("memberInfo",MD5.md5(memberSql),sql);

        String token = AES.AESEncode(userId);

        Map<String, Record> userMap = new HashMap<>();

        userMap.put("memberInfo", memberInfo);

        userMap.put("userInfo",userInfo);

        cache.setex(token, 60 * 60 * 24, userMap);

        ReturnData returnData=new ReturnData(true);
        returnData.setData(token);
        return returnData;

    }

}
